package com.jiezuo.auth.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiezuo.auth.entity.Depart;
import com.jiezuo.auth.entity.Enterprise;
import com.jiezuo.auth.mapper.EnterpriseMapper;
import com.jiezuo.auth.service.DepartService;
import com.jiezuo.auth.service.EnterpriseService;
import com.jiezuo.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 企业管理
 * @author 庞留杰
 * @date 2020/08/26 14:37
 * @version V1.0
 **/
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {

    @Autowired
    EnterpriseMapper mapper;

    @Autowired
    DepartService departService;

    @Override
    public IPage<Enterprise> findPage(Page page, Enterprise enterprise) {
        page.setRecords(mapper.findList(page, enterprise));
        return page;
    }

    @Override
    public List<Enterprise> findList(Enterprise enterprise) {
        return mapper.findList(enterprise);
    }

    @Override
    public Enterprise findById(String id) {
        return mapper.findById(id);
    }

    @Override
    public List<Enterprise> enterpriseTree(Enterprise enterprise) {
        String enterpriseName = enterprise.getName();
        String status = enterprise.getStatus();
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.orderByAsc("created_time");
        List<Enterprise> enterpriseList = this.list(queryWrapper);
        List<Enterprise> enterprises = iterateMenus(enterpriseList, "0", enterpriseName, status);
        return enterprises;
    }

    public List<Enterprise> iterateMenus(List<Enterprise> enterpriseList, String pid, String enterpriseName, String status) {
        List<Enterprise> parents = enterpriseList.stream().filter(it -> pid.equals(it.getPid())).collect(Collectors.toList());
        Iterator<Enterprise> iterator = parents.iterator();
        while (iterator.hasNext()) {
            Enterprise enterprise = iterator.next();
            if ((StringUtil.isNotEmpty(enterpriseName) || StringUtil.isNotEmpty(status))
                    && !isSelfAndChildrenByName(enterpriseList, enterprise, enterpriseName, status)) {
                iterator.remove();//移除
            }
            //获取企业的id
            String enterpriseId = enterprise.getId();
            if (isHasChildren(enterpriseList, enterpriseId)) {
                List<Enterprise> childrens = iterateMenus(enterpriseList, enterpriseId, enterpriseName, status);
                enterprise.setChildren(childrens);
            }
        }
        return parents;
    }

    // 判断是否还有子级
    public boolean isHasChildren(List<Enterprise> enterpriseList, String id) {
        return enterpriseList.stream().filter(it -> id.equals(it.getPid())).findFirst().isPresent();
    }

    // 判断自己和子级中是否包含这个名称和状态（模糊查询）
    public boolean isSelfAndChildrenByName(List<Enterprise> enterpriseList, Enterprise parent, String enterpriseName, String status) {
        boolean isContain;
        if (StringUtil.isNotEmpty(enterpriseName) && StringUtil.isNotEmpty(status)) {
            isContain = parent.getName().contains(enterpriseName) && parent.getStatus().equals(status);
        } else if (StringUtil.isNotEmpty(enterpriseName) && !StringUtil.isNotEmpty(status)) {
            isContain = parent.getName().contains(enterpriseName);
        } else if (!StringUtil.isNotEmpty(enterpriseName) && StringUtil.isNotEmpty(status)) {
            isContain = parent.getStatus().equals(status);
        } else {
            isContain = false;
        }
        isContain = isChildrenContain(enterpriseList, parent.getId(), enterpriseName, status, isContain);
        return isContain;
    }

    public boolean isChildrenContain(List<Enterprise> enterpriseList, String pId, String enterpriseName, String status, boolean isContain) {
        if (!isContain) {//自己不包含，继续查
            List<Enterprise> childrens = enterpriseList.stream().filter(it -> it.getPid().equals(pId)).collect(Collectors.toList());//子级
            for (Enterprise children : childrens) {
                if (StringUtil.isNotEmpty(enterpriseName) && StringUtil.isNotEmpty(status)) {
                    isContain = children.getName().contains(enterpriseName) && children.getStatus().equals(status);
                } else if (StringUtil.isNotEmpty(enterpriseName) && !StringUtil.isNotEmpty(status)) {
                    isContain = children.getName().contains(enterpriseName);
                } else if (!StringUtil.isNotEmpty(enterpriseName) && StringUtil.isNotEmpty(status)) {
                    isContain = children.getStatus().equals(status);
                } else {
                    isContain = false;
                }
                if (isContain) {
                    break;
                }
            }
            if (!isContain) {//子级均不包含,继续
                for (Enterprise children : childrens) {
                    isContain = isChildrenContain(enterpriseList, children.getId(), enterpriseName, status, isContain);
                    if (isContain) {
                        break;
                    }
                }
            }
        }
        return isContain;
    }


    @Override
    public JSONArray enterpriseDepartTree() {
        // 企业
        QueryWrapper<Enterprise> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
        queryWrapper.orderByAsc("created_time");
        List<Enterprise> enterpriseList = this.list(queryWrapper);
        // 部门
        QueryWrapper<Depart> departWrapper = new QueryWrapper<>();
        departWrapper.eq("is_delete", "0");
        departWrapper.orderByAsc("created_time");
        List<Depart> departList = departService.list(departWrapper);
        JSONArray arr = new JSONArray();
        iterateEnterprises(arr, enterpriseList, departList,"0");
        return arr;
    }

    public void iterateEnterprises(JSONArray arr, List<Enterprise> enterpriseList, List<Depart> departList, String pid) {
        List<Enterprise> parents = enterpriseList.stream().filter(it -> pid.equals(it.getPid())).collect(Collectors.toList());
        Iterator<Enterprise> iterator = parents.iterator();
        while (iterator.hasNext()) {
            JSONObject obj = new JSONObject();
            Enterprise enterprise = iterator.next();
            String enterpriseId = enterprise.getId();
            obj.put("row-key", "0_" + enterpriseId);//唯一标识
            obj.put("id", enterpriseId);//编号
            obj.put("code", enterprise.getCode());//编号
            obj.put("name", enterprise.getName());//名称
            obj.put("pid", enterprise.getPid());//上级ID
            obj.put("status", enterprise.getStatus());//是否启用：0否，1是
            obj.put("type", "0");// 0企业，1部门
            JSONArray arr1 = new JSONArray();
            if (isHasChildren(enterpriseList, enterpriseId)) {
                iterateEnterprises(arr1, enterpriseList, departList, enterpriseId);
            }
            JSONArray departArr = new JSONArray();
            iterateDeparts(departArr, departList, enterpriseId, "0");
            arr1.addAll(departArr);
            if (arr1.size() > 0) {
                obj.put("children", arr1);
            }
            arr.add(obj);
        }
    }

    public void iterateDeparts(JSONArray departArr, List<Depart> departList, String enterpriseId, String pid) {
        List<Depart> parents = departList.stream().filter(it -> pid.equals(it.getPid()) && enterpriseId.equals(it.getAffiliation_enterprise())).collect(Collectors.toList());
        Iterator<Depart> iterator = parents.iterator();
        while (iterator.hasNext()) {
            JSONObject obj = new JSONObject();
            Depart depart = iterator.next();
            String departId = depart.getId();
            obj.put("row-key", "1_"+departId);//唯一标识
            obj.put("id", departId);//编号
            obj.put("code", depart.getCode());//编号
            obj.put("name", depart.getName());//名称
            obj.put("pid", depart.getPid());//上级ID
            obj.put("status", depart.getStatus());//是否启用：0否，1是
            obj.put("affiliation_enterprise", depart.getAffiliation_enterprise());//所属企业
            obj.put("type", "1");// 0企业，1部门
            if (isHasChildrenDepart(departList, departId, enterpriseId)) {
                JSONArray arr1 = new JSONArray();
                iterateDeparts(arr1, departList, enterpriseId, departId);
                obj.put("children", arr1);
            }
            departArr.add(obj);
        }
    }

    // 判断是否还有子级
    public boolean isHasChildrenDepart(List<Depart> departList, String id, String enterpriseId) {
        return departList.stream().filter(it -> id.equals(it.getPid()) && enterpriseId.equals(it.getAffiliation_enterprise())).findFirst().isPresent();
    }

}
